package GUITOOl;

import javax.swing.*;
import javax.swing.text.html.HTMLEditorKit;
import javax.swing.text.html.parser.ParserDelegator;
import java.awt.*;
import java.io.*;

/**
 * The type Html to text.
 *
 * @author wyc, zry
 * @version 1.0
 */
public class Html2Text extends HTMLEditorKit.ParserCallback {
    private static Html2Text html2Text = new Html2Text();

    /**
     * The content.
     */
    StringBuffer s;

    /**
     * Instantiates a new Html to text.
     */
    public Html2Text() {
    }

    /**
     * Parse.
     *
     * @param str the str
     * @throws IOException the io exception
     */
    public void parse(String str) throws IOException {

        InputStream iin = new ByteArrayInputStream(str.getBytes());
        Reader in = new InputStreamReader(iin);
        s = new StringBuffer();
        ParserDelegator delegator = new ParserDelegator();
        delegator.parse(in, this, Boolean.TRUE);
        iin.close();
        in.close();
    }

    /**
     * Gets text.
     *
     * @return the text
     */
    public String getText() {
        return s.toString();
    }

    /**
     * Gets content.
     *
     * @param str the str
     * @return the content
     */
    public static String getContent(String str) {
        try {
            html2Text.parse(str);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return html2Text.getText();
    }

    /**
     * Set text in Jlabel.
     *
     * @param jLabel     the jlabel
     * @param longString the long string
     * @throws InterruptedException the interrupted exception
     */
    public static void JlabelSetText(JLabel jLabel, String longString)
            throws InterruptedException {
        StringBuilder builder = new StringBuilder("<html>");
        char[] chars = longString.toCharArray();
        FontMetrics fontMetrics = jLabel.getFontMetrics(jLabel.getFont());
        int start = 0;
        int len = 0;
        while (start + len < longString.length()) {
            while (true) {
                len++;
                if (start + len > longString.length())break;
                if (fontMetrics.charsWidth(chars, start, len)
                        > jLabel.getWidth()) {
                    break;
                }
            }
            builder.append(chars, start, len-1).append("<br/>");
            start = start + len - 1;
            len = 0;
        }
        builder.append(chars, start, longString.length()-start);
        builder.append("</html>");
        jLabel.setText(builder.toString());
    }
}
